#include "spi_bsp.h"

spi_obj_t spi_obj_tbl[SPI_OBJ_NUM_MAX];

void spi_obj_close(spi_obj_id_t obj_id)
{
  spi_obj_t *obj = &spi_obj_tbl[obj_id];
  HAL_SPI_MspDeInit(obj->hspi);
}

int spi_obj_open(spi_obj_id_t obj_id, uint8_t CLKIdleState)
{
  spi_obj_t *obj = &spi_obj_tbl[obj_id];

  switch(obj_id)
  {
#ifdef SPI1_OBJ_EN
  case SPI1_OBJ:
    obj->hspi=&hspi1;
    obj->hspi->Instance = SPI1;
  break;
#endif
#ifdef SPI2_OBJ_EN
  case SPI2_OBJ:
    obj->hspi=&hspi2;
    obj->hspi->Instance = SPI2;
  break;
#endif
#ifdef SPI3_OBJ_EN
  case SPI3_OBJ:
    obj->hspi=&hspi3;
    obj->hspi->Instance = SPI3;
  break;
#endif
  default:
	  break;
  }

  if(obj->hspi ==  NULL)
    return -1;
  if(obj->mutex ==  NULL)
    obj->mutex = xSemaphoreCreateMutex();
  
  obj->hspi->Init.Mode = SPI_MODE_MASTER;
  obj->hspi->Init.Direction = SPI_DIRECTION_2LINES;
  obj->hspi->Init.DataSize = SPI_DATASIZE_8BIT;
  obj->hspi->Init.CLKPolarity = (CLKIdleState == 0) ? SPI_POLARITY_LOW : SPI_POLARITY_HIGH;
  obj->hspi->Init.CLKPhase = SPI_PHASE_2EDGE;
  obj->hspi->Init.NSS = SPI_NSS_SOFT;
  obj->hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
  obj->hspi->Init.FirstBit = SPI_FIRSTBIT_MSB;
  obj->hspi->Init.TIMode = SPI_TIMODE_DISABLE;
  obj->hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  obj->hspi->Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(obj->hspi) != HAL_OK)
  {
    Error_Handler();
  }

  return 0;
}

int spi_obj_read(spi_obj_id_t obj_id, uint8_t *buf, int size)
{
  int ret;
  spi_obj_t *obj = &spi_obj_tbl[obj_id];
  
  if(obj_id >= SPI_OBJ_NUM_MAX || buf == NULL || size == 0)
    return -1;
  xSemaphoreTake(obj->mutex,portMAX_DELAY); 
  ret = HAL_SPI_Receive(obj->hspi, (uint8_t *)buf, size, 1000)==HAL_OK ? size:-1;   
  xSemaphoreGive(obj->mutex); 
  
  return ret;
}

int spi_obj_write(spi_obj_id_t obj_id, uint8_t *buf, int size)
{
  int ret;
  spi_obj_t *obj = &spi_obj_tbl[obj_id];
  
  if(obj_id >= SPI_OBJ_NUM_MAX || buf == NULL || size == 0)
    return -1;
  xSemaphoreTake(obj->mutex,portMAX_DELAY); 
  ret = HAL_SPI_Transmit(obj->hspi, (uint8_t *)buf, size, 1000)==HAL_OK ? size:-1;   
  xSemaphoreGive(obj->mutex); 
  
  return ret;
}






